package com.wang.tasker.core;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GlobalConfig {
	
	private final String CONFIG_FILE_PATH = "conf" + File.separator + "settings.xml";
	
	private File configFile;
	
	private ConfigElement configEle;
	
	private static Logger logger = LoggerFactory.getLogger(GlobalConfig.class);
	
	private HashMap<String, String> taskList = new HashMap<String, String>();

	public void init() throws DocumentException{
		String jtaskerHome = System.getProperty("jtasker.home");
		configFile = new File(jtaskerHome + File.separator + CONFIG_FILE_PATH);
		
		if(!configFile.exists()){
			configFile = new File(CONFIG_FILE_PATH);
			if(!configFile.exists())
				throw new RuntimeException("Config file is not exist! File:" + configFile.getAbsolutePath());
		}
		
		logger.debug("Load config file:{}", configFile.getAbsoluteFile());
		
		configEle = new ConfigElement(configFile);
		
		List<ConfigElement> taskTypeList = configEle.selectElements("//TaskType/Type");
		for(int i=0;i<taskTypeList.size();i++){
			ConfigElement taskTypeEle = taskTypeList.get(i);
			String taskTypeName = taskTypeEle.attributeValue("Name");
			String taskTypeClass = taskTypeEle.attributeValue("Class");
			logger.debug("Load task type : [{}@{}]", taskTypeName, taskTypeClass);
			TaskFactory.addType(taskTypeName, taskTypeClass);
		}
	}
	
	public ConfigElement getShareConfig(String refName){
		return configEle.selectSingleElement("//ConfigManagement/Config[@Name='" + refName + "']");
	}
	
	
	
	public String getContent(){
		return configEle.getElement().asXML();
	}
}
